#include <sys/socket.h>
#include "common.h"

int createServerSocket()
{
	int fd;
	int reUse=1;
	int flags ;
	struct sockaddr_in address;
	fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(-1 == fd)
	{
		printf("[createServerSocket]	socket(...) return -1\n");
		goto error;
	}	
	printf("[createServerSocket]	create listening socket succeed, fd:	%d\n",fd);
	//create socket succeed
	
	if(-1 == setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reUse, sizeof(reUse))
	{	
		printf("[createServerSocket]	set socket SO_REUSEADDR fail...\n");
		goto error;
	}
	
	//try to bind
	bzero(&address,sizeof(struct sockaddr_in));
	address.sin_family=AF_INET;
	address.sin_addr.s_addr = htonl(INADDR_ANY);
	address.sin_port = htons( 6666 );
	if( -1 == bind(fd, &address , sizeof(struct sockaddr_in))
	{
		printf("[createServerSocket]	bind socket fail...\n");
		goto error;
	}
	
	//try to set non_block
	if( -1 == fcntl(fd, F_GETFL))
	{
		printf("[createServerSocket]	fcntl socket [get] fail...\n");
        goto error;
    }
	
    if( -1 == fcntl(fd, F_SETFL, flags | O_NONBLOCK) ) 
	{
		printf("[createServerSocket]	fcntl socket [set] fail...\n");
        goto error;
    }
	//try to listen
	if( -1 == listen(fd,1024) )
	{
		printf("[createServerSocket]	listen socket fail...\n");
		goto error;
	}
	printf("[createServerSocket]	socket [ create | reuse | bind | non_block | listen ] succeed!\n");
	return fd;
	
	error:
		if(fd >= 0 )
		{		
			close(fd);
		}
		return OPEN_DCHAT_ERROR;
	
}